package cn.itcast.flink.parallelism;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


/**
 * @author lilulu
 */
public class WordCountParallelism {
    public static void main(String[] args) throws Exception {
        ParameterTool fromArgs = ParameterTool.fromArgs(args);
        if (fromArgs.getNumberOfParameters() != 2) {
            System.out.println("Usage: WordCount --host <host> --port <port> ....................");
            System.exit(-1);
        }
        String host = fromArgs.get("host");
        int port = fromArgs.getInt("port", 9999);
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        // 2. 数据源-source
        DataStreamSource<String> source = env.socketTextStream(host, port);
        // 3. 数据转换-transformation
        SingleOutputStreamOperator<Tuple2<String, Integer>> resultData = source.flatMap(
                new FlatMapFunction<String, String>() {
                    public void flatMap(String lines, Collector<String> collector) throws Exception {
                        String[] words = lines.trim().split("\\s+");
                        for (String word : words) {
                            collector.collect(word);
                        }
                    }
                }
        ).map(
                new MapFunction<String, Tuple2<String, Integer>>() {
                    public Tuple2<String, Integer> map(String word) throws Exception {
                        return Tuple2.of(word, 1);
                    }
                }
        ).keyBy(0).sum(1);
        // 4. 数据终端-sink
        resultData.print();
//        resultData.print().setParallelism(1);
        // 5. 触发执行-execute
        env.execute("WordCountParallelism");
    }
}